package setting

import (
	"log"
	"time"

	"github.com/go-ini/ini"
)

var (
	// Cfg record the config info
	Cfg *ini.File

	// RunMode gin run as debug or release mode
	RunMode string

	// HTTPHost show the websocket server port
	HTTPHost string

	// HTTPPort show the http server port
	HTTPPort int

	// RPCPort show the Grpc server port
	RPCPort int

	// WEBSocketPort show the websocket server port
	WEBSocketPort int

	// ReadTimeout set the read timeout time
	ReadTimeout time.Duration

	// WriteTimeout set the read timeout time
	WriteTimeout time.Duration

	// AlarmURL set the alarm center address url
	AlarmURL string

	// tokenURL set the get token address from alarm center
	TokenURL string

	// AlarmUserName set the username to get token
	AlarmUserName string

	// AlarmPassWord set the password go get token
	AlarmPassWord string

	DataBaseUser string
	PassWord     string
	Host         string
	DataBaseName string

	FileSRC string
)

func init() {
	var err error
	Cfg, err = ini.Load("conf/conf.ini")
	if err != nil {
		log.Fatalf("Fail to parse 'conf/conf.ini': %v", err)
	}

	LoadBase()
	LoadServer()
	LoadAlarm()
	LoadDataBase()
	LoadFile()
}

// LoadBase load base info from conf.ini
func LoadBase() {
	RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
}

// LoadServer load server info from conf.ini
func LoadServer() {
	sec, err := Cfg.GetSection("server")
	if err != nil {
		log.Fatalf("Fail to get section 'server': %v", err)
	}

	RPCPort = sec.Key("RPC_PORT").MustInt(6061)
	WEBSocketPort = sec.Key("WEB_SOCKET_PORT").MustInt(7070)
	HTTPPort = sec.Key("HTTP_PORT").MustInt(6060)
	HTTPHost = sec.Key("HTTP_HOST").MustString("10.0.105.45")
	ReadTimeout = time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
	WriteTimeout = time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second
}

func LoadAlarm() {
	sec, err := Cfg.GetSection("alarm")
	if err != nil {
		log.Fatalf("Fail to get section 'alarm': %v", err)
	}
	AlarmURL = sec.Key("dangerURl").MustString("http://121.40.178.60:30351/api/danger")

	TokenURL = sec.Key("tokenURL").MustString("http://121.40.178.60:30351/api/user/login")

	AlarmUserName = sec.Key("userName").MustString("shixx")

	AlarmPassWord = sec.Key("password").MustString("000000")

}

func LoadDataBase() {
	sec, err := Cfg.GetSection("database")
	if err != nil {
		log.Fatalf("Fail to get section 'database': %v", err)
	}
	DataBaseUser = sec.Key("USER").MustString("root")
	PassWord = sec.Key("PASSWORD").MustString("123456")
	Host = sec.Key("HOST").MustString("0.0.0.0:3306")
	DataBaseName = sec.Key("NAME").MustString("rest_api_example")
}

func LoadFile() {
	sec, err := Cfg.GetSection("file")
	if err != nil {
		log.Fatalf("Fail to get section 'file': %v", err)
	}
	FileSRC = sec.Key("fileSrc").MustString("/data/runtime/upload/")
}
